<template>
  <div class="app-container">
    <el-card class="box-card" style="margin: 10px">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="挂号单ID" prop="registrationId">
          <el-input placeholder="请输入挂号单" v-model="queryParams.registrationId" clearable
            @keyup.enter.native="handleQuery"></el-input>
        </el-form-item>

        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
        <el-button type="warning" icon="el-icon-search" size="mini">读取IC卡</el-button>
      </el-form>
    </el-card>

    <div v-show="xianshi">
      <el-card class="box-card" style="margin: 10px">
        <el-descriptions>
          <el-descriptions-item label="挂号单号">{{ registration.registrationId }}</el-descriptions-item>
          <el-descriptions-item label="医生姓名">{{ doctor.doctName }}</el-descriptions-item>
          <el-descriptions-item label="科室名称">{{ dept.deptName }}</el-descriptions-item>
          <el-descriptions-item label="患者姓名">{{ patient.patientName }}</el-descriptions-item>
          <el-descriptions-item label="就诊时间">{{ registration.registrationNo }}</el-descriptions-item>
          <el-descriptions-item label="主诉">{{ treat.treatComplaint }}</el-descriptions-item>
          <el-descriptions-item label="诊断信息">{{ treat.treatInfo }}</el-descriptions-item>
        </el-descriptions>
      </el-card>

      <el-card class="box-card" style="margin: 10px">
        <el-row>
          <!-- <el-button type="primary" icon="el-icon-shopping-cart-full"
            >全选</el-button
          >
          <el-button type="success" icon="el-icon-shopping-cart-2"
            >取消全选</el-button
          > -->
          <el-button type="danger" icon="el-icon-files" @click="send">确定发药</el-button>

        </el-row>
      </el-card>

      <el-card class="box-card" style="margin: 10px">
        <el-row> 【药品处方】【处方总额】:人民币 <span>{{ sumAmout.toFixed(1) }} 元</span> </el-row>


        <el-table v-loading="loading" :data="prescriptionList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="序号" align="center" type="index" :index="indexMethod" />
          <el-table-column label="药品名称" align="center" prop="medicineId">
            <template slot-scope="scope">
              <span>{{ getMedicineName(scope.row.medicineId) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="数量" align="center" prop="quantity" />
          <!-- <el-table-column label="单价" align="center" prop="deptNum" /> -->
          <el-table-column label="金额（元）" align="center" prop="amount" />
          <el-table-column label="服用备注" align="center" prop="notes" />
          <el-table-column label="支付状态" align="center" prop="state">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.his_prescription_state" :value="scope.row.state" />
            </template>
          </el-table-column>
        </el-table>

      </el-card>
    </div>
    <!-- 如果没有输入订单号或订单号错误，显示页面 -->
    <div v-show="enrro">
      <h2 style="color: red; text-align: center">请输入正确的挂号单号ID查询</h2>
    </div>
  </div>
</template>

<script>
//支付组件


import { getRegistration } from "@/api/his/registration";
import { getPatient } from "@/api/his/patient";
import { getTreatByRegId } from "@/api/his/treat";
import { getScheduleById } from "@/api/his/schedule";
import { getDoctor } from "@/api/his/doctor";
import { getDept } from "@/api/his/dept";
import { listPrescription, getPrescription, delPrescription, addPrescription, updatePrescription } from "@/api/his/prescription";
import { listMedicine, getMedicine, delMedicine, addMedicine, updateMedicine } from "@/api/his/medicine";
export default {
  name: "Prescription",
  dicts: ['his_prescription_state'],
  //计算药品总金额
  computed: {
    sumAmout() {
      return this.prescriptionList
        .map(row => row.amount)
        .reduce((acc, cur) => parseFloat(cur) + acc, 0);
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      // total: 0,
      buy_code: false,
      xianshi: false,
      enrro: true,

      registration: [], //挂号
      patient: [],
      treat: [],
      schedule: [],
      dept: [],
      doctor: [],
      prescriptionList: [],

      // 药品数据
      medicineList: [],
      // 药品查询参数
      queryParamsM: {
        pageNum: 1,
        pageSize: 10,
        medicineName: null,
        medicineType: null,
        keyword: null,
        prescribe: null,
        factoryId: null,
        status: null,
      },

      //选中行的状态（多个，这只是测试）
      PState: 1,
      // 查询参数
      queryParams: {
        registrationId: null,
      },
      //处方药品查询参数
      queryParamsP: {
        pageNum: 2,

        treatId: null,
      },
      // 表单参数
      form: {},
    };
  },
  created() {
    this.getmedicineList();
  },
  methods: {
    // 查询所有药品信息
    getmedicineList() {
      // 查询药品信息
      listMedicine(this.queryParamsM).then(response => {
        this.medicineList = response.rows;
        console.log("所有药品：");
        console.log(this.medicineList);
      });
    },
    // 根据medicineId获取药品名称
    getMedicineName(medicineId) {
      const medicine = this.medicineList.find((item) => item.medicineId === medicineId);
      return medicine ? medicine.medicineName : '未命名药品';
    },
    /** 根据挂号ID查询挂号详情 */
    getRegistrations() {
      getRegistration(this.queryParams.registrationId).then((response) => {
        console.log(response);
        if (response.data != null) {
          //如果返回成功,显示具体窗口
          this.xianshi = true;
          this.enrro = false;
          this.registration = response.data;


          //console.log(this.registration);
          /** 根据患者ID查询患者详情 */
          getPatient(this.registration.registrationPatientId).then(
            (response1) => {
              this.patient = response1.data;
              console.log(this.patient);
            }
          ),
            /** 根据挂号Id查询就诊（病例）详情 */
            getTreatByRegId(this.queryParams.registrationId).then(
              (response2) => {
                // 当就诊（病例）详情为空时，直接设置状态并停止后续操作
                // 修复输入错误挂号ID后再次输入正确挂号ID无法正常加载的问题
                if (response2.data == null) {
                  this.xianshi = false;
                  this.enrro = true;
                  this.queryParams.registrationId = null;
                  this.loading = true; // 确保加载状态为默认值
                  return; // 停止执行后续代码
                }

                //缓存病例信息
                this.treat = response2.data;
                //更新缓存的开药单查询参数
                this.queryParamsP.treatId = this.treat.treatId;

                /** 根据就诊ID查询处方药品列表，即开药单 */
                listPrescription(this.queryParamsP).then((responseP => {
                  this.prescriptionList = responseP.rows;
                  this.total = responseP.total;
                  this.loading = false;
                }))
              }
            ),
            /** 根据排班Id查询排班详情 */
            getScheduleById(this.registration.registrationSchedule).then(
              (response3) => {
                this.doctor.doctId = response3.data.doctId;
                /** 根据医生Id查医生 */
                getDoctor(this.doctor.doctId).then(
                  (response4) => {
                    this.doctor = response4.data;
                    console.log(this.doctor)
                    getDept(this.doctor.deptId).then((response5) => {
                      this.dept = response5.data
                    })
                  }
                )
              }
            );

        } else {
          this.xianshi = false;
          this.enrro = true;
          this.registration.registrationId = 0;
        }
      });
    },
    getAllPrescription() {
      /** 根据就诊ID查询药品处方列表，即开药单 */
      listPrescription(this.queryParamsP).then((responseP) => {
        this.prescriptionList = responseP.rows;
        this.total = responseP.total;
        this.loading = false;
      });
    },
    getPatient() {
      getPatient(this.registration.p);
    },
    handleChange(value) { },
    /** 搜索按钮操作 */
    handleQuery() {
      //this.queryParamsP.pageNum = 1;
      this.getRegistrations();
      // this.listPrescriptions();

    },
    /** 发药按钮操作 */
    async send() {
      console.log("开药单：");
      console.log(this.prescriptionList);
      //只有状态为已支付才能发药
      //检查处方列表中是否存在state为1（未支付）或2（已发药）的条目
      const hasUnsuitableState = this.prescriptionList.some(
        prescription => prescription.state == 1 || prescription.state == 2
      );
      // 如果存在不合适的状态，调用err方法
      if (hasUnsuitableState) {
        this.err('发药错误，包含未缴费项或已发药完成');
      }
      // 如果所有处方都已支付，继续执行发药的操作
      else {
        let flag = 0;
        // 遍历处方列表
        for (const prescription of this.prescriptionList) {
          // 在药品列表中查找与当前处方ID匹配的药品
          const medicine = this.medicineList.find(
            item => item.medicineId == prescription.medicineId
          );
          // 如果找到了药品并且库存不足
          if (medicine && medicine.stock < prescription.quantity) {
            // 调用错误提示
            console.log(`药品${medicine.medicineName}的库存不足`);
            await this.err(`药品${medicine.medicineName}的库存不足`);
            flag = 1;
          }
        }
        if (flag == 1) {
          return; // 发现库存不足后直接退出函数
        }

        // ********************************发药，修改开药单（药品处方表）的状态*******************************************
        console.log('所有处方已支付且库存够，可以发药');
        const unsendPrescriptions = this.prescriptionList;
        // 创建一个Promise.all来并行处理所有更新请求，这比逐个调用更高效
        const updatePromises = unsendPrescriptions.map(prescription => {
          // 假设updatePrescription接受一个对象，包含需要更新的id和新的state
          return updatePrescription(
            {
              prescriptionId: prescription.prescriptionId,
              // 表示已发药
              state: 2
            }
          );
        });
        // 使用Promise.all等待所有更新操作完成
        Promise.all(updatePromises)
          .then(responses => {
            // 所有更新成功后的回调处理
            console.log('所有药品发放成功');
            // 刷新列表
            this.getAllPrescription();
          })
          .catch(error => {
            // 更新过程中如果有任何错误，可以在这里处理
            console.error('更新处方状态时发生错误:', error);
          });

        // ************************************发药，修改药品表的库存（减少库存）****************************************************
        console.log('开始减少药品库存');
        console.log('减少前');
        console.log(this.medicineList);

        // 准备更新药品库存的请求
        const stockUpdatePromises = unsendPrescriptions.map(prescription => {
          // 查找对应的药品以获取当前的库存信息
          const medicine = this.medicineList.find(item => item.medicineId === prescription.medicineId);
          // 确保找到了药品且库存足够
          if (medicine && medicine.stock >= prescription.quantity) {
            // 计算新的库存量
            const newStock = medicine.stock - prescription.quantity;
            // 准备更新库存的数据
            const updateStockData = {
              medicineId: medicine.medicineId,
              stock: newStock,
            };
            console.log('新数据');
            console.log(updateStockData);
            // 返回更新库存的Promise
            return updateMedicine(
              {
                medicineId: medicine.medicineId,
                medicineName: medicine.medicineName,
                medicineNo: medicine.medicineNo,
                factoryId: medicine.factoryId,
                medicineType: medicine.medicineType,
                prescribe: medicine.prescribe,
                unit: medicine.unit,
                price: medicine.price,
                stock: newStock,
                warn: medicine.warn,
                conversion: medicine.conversion,
                status: medicine.status,
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null,
                keyword: medicine.keyword
              }
            ); // updateMedicine是更新药品信息的方法
          } else {
            // 如果找不到药品或库存不足，这里可以选择抛出错误或忽略，根据业务需求调整
            this.err(`无法减少药品${prescription.medicineId}的库存，原因可能是库存不足或药品信息缺失.`);
            return Promise.resolve(); // 或者 throw new Error('库存更新失败');
          }
        });
        // 并行处理所有库存更新请求
        Promise.all(stockUpdatePromises)
          .then(responses => {
            console.log('所有药品库存减少操作成功');
            // 可能需要进一步处理响应或刷新相关数据
          })
          .catch(error => {
            console.error('更新药品库存时发生错误:', error);
            // 处理库存更新失败的情况
          });
        this.getmedicineList();
        console.log('减少后');
        console.log(this.medicineList);
      }
    },

    /** 状态错误提示，接受一个错误消息作为参数 */
    err(errorMessage) {
      this.$message.error(errorMessage);
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.inspectId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    indexMethod(index) {
      return index + 1;
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

  },
};
</script>
